﻿package com.zjht.gmcc.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.zjht.gmcc.bean.SessionListener;
import com.zjht.gmcc.bean.model.UserSession;

import com.zjht.gmcc.bean.util.Menu;
import com.zjht.gmcc.bean.util.MyCode;
import com.zjht.gmcc.bean.util.MyConstant;
import com.zjht.gmcc.bean.util.MyFormat;
import com.zjht.gmcc.bean.util.MyJDBC;
import com.zjht.gmcc.bean.util.MyParam;
import com.zjht.gmcc.bean.util.MyParamUtil;
import com.zjht.gmcc.bean.util.MySession;

public class CheckUser extends HttpServlet {
	private static final long serialVersionUID = -7041469135607580016L;

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		response.setContentType("text/html");
		response.setCharacterEncoding("GBK");
		request.setCharacterEncoding("GBK");// 中文
		PrintWriter out = new PrintWriter(response.getOutputStream());
		String js = "var w=window.parent.document;w.frames.myimg.location.reload();w.all.checkcode.value='';var u=w.all['usercode'];if(u!=null)u.focus();";
		MyJDBC myJDBC = null;
		try {
			Object rand = session.getAttribute("rand");
			String checkcode = request.getParameter("checkcode");
			if (rand == null || checkcode == null || !rand.equals(checkcode)) {
				out.print("<script>alert('对不起，验证码错误，请重新输入验证码！');");
				out.print(js);
				out.print(" w.all.checkcode.focus();</script>");
				out.flush();
				out.close();
				return;
			}

			String strOK = request.getParameter("ok");
			boolean isNew = true;
			if ("0".equals(strOK))
				return;
			else if ("1".equals(strOK))
				isNew = false;

			String s_usercode = request.getParameter("usercode").trim().toUpperCase();
			String s_userpwd = request.getParameter("userpwd");

			String jm_userpwd = MyCode.MD5(s_userpwd);

			myJDBC = new MyJDBC();
			// 检测密码
			String s_sql = "SELECT OperID,OperName,OrgaCode, DeptID FROM OPERS WHERE OperCode = ? AND PassWD = ? AND status='1'";
			PreparedStatement ps = myJDBC.prepareStatement(s_sql);
			ps.setString(1, s_usercode);
			ps.setString(2, jm_userpwd);
			ResultSet rs = ps.executeQuery();
			if (!rs.next()) {
				out.print("<script>alert('用户名或密码错误。请您重试。');");
				out.print(js);
				out.print("</script>");
				out.flush();
				out.close();
				return;
			}
			int userid = rs.getInt("OperID");
			String username = rs.getString("OperName");
			String orgcode = rs.getString("OrgaCode");
			int deptid = rs.getInt("DeptID");

			// 检测组织是否停用
			s_sql = "SELECT OrgID,ShortName organame,OrgaTypeID,ActorCode,AreaID,channeltype FROM ORGANIZA WHERE OrgaCode = ? AND status='1'";
			ps = myJDBC.prepareStatement(s_sql);
			ps.setString(1, orgcode);
			rs = ps.executeQuery();
			if (!rs.next()) {
				out.print("<script>alert('对不起！您所在的组织已被停用，无法登录。请您与管理员联系。');");
				out.print(js);
				out.print("</script>");
				out.flush();
				out.close();
				return;
			}
			int orgid = rs.getInt("OrgID");
			String orgname = rs.getString("OrgaName");
			int orgtype = rs.getInt("OrgaTypeID");
			String actorcode = rs.getString("ActorCode");
			int areaid = rs.getInt("AreaID");
			String channeltype = rs.getString("channeltype");

			if (isNew && SessionListener.IsLogoned(s_usercode)) {
				out.print("<form name='formok' method='post' action=''><input name='usercode' type='hidden' value='");
				out.print(s_usercode);
				out.print("' /><input name='userpwd' type='hidden' value='");
				out.print(s_userpwd);
				out.print("' /><input name='checkcode' type='hidden' value='");
				out.print(checkcode);
				out.print("' /></form><script>var isOK='0';if(confirm('此 ");
				out.print(s_usercode);
				out.print(" 帐号目前处于在线状态，可能是您未正常退出，或有人已在别处登录。\\n\\r\\n\\r是否继续登录？')){isOK='1';}else{ ");
				out.print(js);
				out.print(" }document.all.formok.action='CheckUser?ok='+isOK;document.all.formok.submit();</script>");
				out.flush();
				out.close();
				return;
			}

			int dutyid = -1;
			s_sql = "SELECT dutyid FROM operspopedom WHERE OperCode = ?";
			ps = myJDBC.prepareStatement(s_sql);
			ps.setString(1, s_usercode);
			rs = ps.executeQuery();
			if (rs.next()) {
				dutyid = rs.getInt("DutyID");
			}

			String strIP = request.getRemoteAddr();
			// String strHost = request.getRemoteHost();

			// 取用户菜单
			String s_menuid = "";
			s_sql = "SELECT menuid FROM MENU WHERE menuid IN (SELECT b.menuid FROM OPERSPOPEDOM a, DUTYPOPEDOM b WHERE  a.opercode=? AND a.dutyid = b.dutyid ) AND (status = '1' OR status = '2') AND (channeltype='all' OR channeltype LIKE ?) AND (orgcode is null OR orgcode LIKE ?) ORDER BY dispid";
			ps = myJDBC.prepareStatement(s_sql);
			ps.setString(1, s_usercode);
			ps.setString(2, "%" + channeltype + "%");
			ps.setString(3, "%," + orgcode + ",%");
			boolean isEChannelCITY = true;// 是否为市移动独立操盘的电子渠道
//			if (MyConstant.ORGTYPE_CITYMOBILE == orgtype) {// 如果是市移动人员登录，则要识别是否为市移动独立操盘的电子渠道
//				isEChannelCITY = MyParam.hEChannelAreaIDToAreaName.get(areaid) == null;
//			}
			rs = ps.executeQuery();
			if (isEChannelCITY) {// 如果是市独立操盘或非电子渠道用户，则无需要处理菜单
				while (rs.next()) {
					s_menuid += rs.getString(1) + ",";
				}
			} else {// 如果是采用全省统一操盘的市移动用户，则需要屏蔽独立操盘电子渠道相关菜单
				int menuid = 0;
				boolean addMenu = true;// 是否需要添加菜单
				while (rs.next()) {
					menuid = rs.getInt(1);
					addMenu = true;
					if (menuid >= Menu.ECHANNEL && menuid < Menu.ECHANNEL + 100) {
						addMenu = false;
						for (int i = 0; i < Menu.ECHANNEL_GMCC_CITY_MENUS.length; i++) {
							if (menuid == Menu.ECHANNEL_GMCC_CITY_MENUS[i]) {
								addMenu = true;
								break;
							}
						}
					}
					if (addMenu)
						s_menuid += menuid + ",";
				}
			}
			// 如果用户没有任何菜单权限
			if (s_menuid.length() == 0) {
				session.invalidate();
				out.print("<script>alert('对不起，您无权登录本系统！请联系管理员！');");
				out.print(js);
				out.print("</script>");
				out.flush();
				out.close();
				return;
			}
			session.setAttribute(MySession.USER_MENUID_ALL, s_menuid);// 用户所有菜单的id号,用逗号间隔，并以逗号结尾
			rs.close();

			session.setAttribute("USER_DETAIL", "`" + areaid + "#" + username + "#" + orgname + "#" + strIP + "#" + MyFormat.getTodayFull());// 用户IP和登录时间等

			String deptname = MyParamUtil.getDeptName(deptid);

			SessionListener.UpdateSession(session, s_usercode);
			session.setAttribute(MySession.USER, new UserSession(userid, s_usercode, username, orgid, orgcode, orgname, orgtype, channeltype, deptid,
					deptname, dutyid, actorcode, areaid));

			try {
				s_sql = "INSERT INTO USERLOGON (opercode,ip,logondate) VALUES(?,?,SYSDATE)";
				ps = myJDBC.prepareStatement(s_sql);
				ps.setString(1, s_usercode);
				ps.setString(2, strIP);
				ps.executeUpdate();
			} catch (Exception exx) {
				// exx.printStackTrace();
				System.out.println("CheckUser.java(Insert into userlogon) error");
			} finally {
				MyJDBC.close(myJDBC);
			}

//			Task.TaskMsg(session);// (新消息,已查看消息)
			session.setAttribute(MySession.TASK_FIRSTRELOAD, "1");
			// session.setAttribute(MyConstant.TASK_ZERODEPOTRESET,Task.intZeroDepotReset+"");
			session.removeAttribute("rand");
			out
					.print("<script>if(parent!=null&&parent.name=='mainFrame'){ parent.parent.leftFrame.document.body.onbeforeunload=function(){};parent.parent.leftFrame.document.body.onunload=function(){};}");
			out
					.print("	var win = window.open('sysframe/first.jsp','_manage','scroll=no,toolbar=no,menubar=no,titlebar=yes,directories=no,resizable=yes,status=yes,fullscreen=no,top=0,left=0,width=900,height=700');");
			out.print("	win.moveTo(0,0);");
			out.print("	win.resizeTo(screen.availWidth,screen.availHeight);");
			out.print("	if(window.parent.name!='_manage'){ ");
			out.print("		window.parent.opener=null;window.parent.close();");
			out.print("}</script>");
			out.flush();
			out.close();
		} catch (Exception e) {
			out.println("<script>alert('对不起，您在登录时遇到了问题，请联系系统管理员！');");
			out.print(js);
			out.print("</script>");
			out.flush();
			out.close();
			return;
		} finally {
			MyJDBC.close(myJDBC);
		}
	}
}
